package org.domain.demo.session.user;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.faces.model.SelectItem;

import org.domain.demo.entity.Books;
import org.domain.demo.session.query.BookQuery;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.FlushModeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.international.StatusMessage.Severity;

@Stateful
@Name("bookMaintain")
public class BookStoreBean implements BookStore {
	
	@In
	private StatusMessages statusMessages;
	
    @In(create=true)
    @Out(required=false)
    private BookQuery bookQuery;
    
    @Out(scope=ScopeType.PAGE)
    private List<Books> booksDataModel;
    
    @In(required=false)
    @Out(required=false)
    private String address;
    
    @In(required=false)
    @Out(required=false)
    private String payment;
    
    @In(required=false)
    @Out(required=false)
    private String bank;
    
    @Out(required=false)
    private Long totalPrice = 0l;
    
    @Out(required=false)
    private List<SelectItem> addressSelectList;
    
    @Out
    private List<Books> selectedBooks;
	
	@Begin(join = true, flushMode = FlushModeType.MANUAL)
	public String initBookStore(){
		booksDataModel = new ArrayList<Books>();
		selectedBooks = new ArrayList<Books>();
		addressSelectList = new ArrayList<SelectItem>();
		addressSelectList.add(new SelectItem("Shanghai","Shanghai"));
		addressSelectList.add(new SelectItem("Beijing","Beijing"));
		addressSelectList.add(new SelectItem("Guangzhou","Guangzhou"));
		addressSelectList.add(new SelectItem("Hangzhou","Hangzhou"));
		return "";
	}

	public String selectBook(Books b) {
		b.setSelected(true);
		return "";
	}

	public String confirmSelectBook() {
		Iterator<Books> it = booksDataModel.iterator();
		while(it.hasNext()){
			Books b = it.next();
			if(b.isSelected()){
				selectedBooks.add(b);
				totalPrice+=b.getPrice();
			}
		}
		return "payment";
	}
	
	public String confirmAndPay() {
		statusMessages.addFromResourceBundle(Severity.INFO,"book.payment.confirmed");
		return "success";
	}

	public void searchBook() {
		booksDataModel = bookQuery.getResultList();
	}

	public String selectPayment() {
		
		System.out.println(payment);
		System.out.println(bank);
		
		return "confirm";
	}

	@Destroy
	@Remove
	public void destroy() {}

	@End
	public String cancel() {
		return "cancel";
	}

	public void changePayment() {
		if(payment.equals("e-bank")){
			bank = "";
		}
	}

}
